#!/bin/bash -x

# install rpms on a Fedora 22 system to prepare it for kpatch integration tests

set -o errexit

[[ $UID != 0 ]] && sudo=sudo

warn() {
	echo "ERROR: $1" >&2
}

die() {
	warn "$@"
	exit 1
}

install_rpms() {
	# crude workaround for a weird dnf bug where it fails to download
	$sudo dnf install -y $* || $sudo dnf install -y $*
}

install_rpms gcc elfutils elfutils-devel pesign openssl numactl-devel wget patchutils

$sudo dnf builddep -y kernel || $sudo dnf builddep -y kernel

# install kernel debuginfo and devel RPMs for target kernel
kverrel=$(uname -r)
kverrel=${kverrel%.x86_64}
kver=${kverrel%%-*}
krel=${kverrel#*-}
install_rpms https://kojipkgs.fedoraproject.org/packages/kernel/$kver/$krel/x86_64/kernel-debuginfo-$kver-$krel.x86_64.rpm https://kojipkgs.fedoraproject.org/packages/kernel/$kver/$krel/x86_64/kernel-debuginfo-common-x86_64-$kver-$krel.x86_64.rpm https://kojipkgs.fedoraproject.org/packages/kernel/$kver/$krel/x86_64/kernel-devel-$kver-$krel.x86_64.rpm

# install version of gcc which was used to build the target kernel
gccver=$(gcc --version |head -n1 |cut -d' ' -f3-)
kgccver=$(readelf -p .comment /usr/lib/debug/lib/modules/$(uname -r)/vmlinux |grep GCC: | tr -s ' ' | cut -d ' ' -f6-)
if [[ $gccver != $kgccver ]]; then
	gver=$(echo $kgccver | awk '{print $1}')
	grel=$(echo $kgccver | sed 's/.*-\(.*\))/\1/')
	grel=$grel.$(rpm -q gcc |sed 's/.*\.\(.*\)\.x86_64/\1/')
	install_rpms https://kojipkgs.fedoraproject.org/packages/gcc/$gver/$grel/x86_64/cpp-$gver-$grel.x86_64.rpm https://kojipkgs.fedoraproject.org/packages/gcc/$gver/$grel/x86_64/gcc-$gver-$grel.x86_64.rpm https://kojipkgs.fedoraproject.org/packages/gcc/$gver/$grel/x86_64/libgomp-$gver-$grel.x86_64.rpm
fi

install_rpms ccache
ccache -M 5G
